from lowlevel import *
import urllib2,urllib,time
API_Key="59a5d7fa32f755407c332cb79e4ddbf4"
secret="f6820c1d8e4f0e6d6d69ea7ec4a01578"
api_url="http://ws.audioscrobbler.com/2.0/?api_key="+API_Key+"&autocorrect=1&method="
def query(method,l_artist="",l_album="",l_track=""):
    try:
        url=api_url+method
        if method=="artist.getTopTags" or method=="artist.getCorrection":
            url=url+"&artist="+urllib.quote_plus(su(l_artist))
        if method=="track.getinfo":
            url=url+"&artist="+urllib.quote_plus(su(l_artist))+"&track="+urllib.quote_plus(su(l_track))
        page=urllib2.urlopen(url).read()
    except urllib2.HTTPError,e:
        error_page=e.read()
        if"<lfm status=\"failed\">" in error_page:
            print urllib.quote_plus(su(l_artist))+"not_in_database"
            return "not_in_database"
        print "Unkown"
        return "unknown"
    except:
        print "unknown"
        return "unknown"
                
    return page
def nachbrenner(artist,title):
    print "nachbrenner"
    album=mb_album(artist,title)
    derp=(album,lm_picture(artist,album))
    print "nachbrenner erfolgreich" + album
    return derp
    
    
def parse(text,*keywords):
    wert=text
    for word in keywords:
        wert=getfield(wert,word)[0]
    return wert
def enter_wait(self):  
    while True:
        time.sleep(10)
        print str(type(self))+str(type(self).workersout)
        nicestring=""
        try:
            for key,value in type(self).local.iteritems():
                if (value!="work"):
                    nicestring=nicestring+su(key) +"\r"+su(value)+"\n"
            with open(filename(self)+'.txt','w') as f:
                f.write(nicestring)
        except RuntimeError:pass
        if type(self).workersout==0:
            break
def parse_genre(text):
    pointer=0
    tags=list()
    for i in range(10):
            tag=getfield("name",text,pointer)
            size=getfield("count",text,pointer)
            if(size!="" and tag!=""):
                    try:
                            if(int(size[0])>75):
                                    tags.append(tag[0])
                                    #print tag[0]

                    except ValueError,msg:
                            derp=str(msg)[str(msg).find("ValueError"):]
                            continue
                    pointer=size[1]
    genre_tag=makeid3(tags)
    if (genre_tag==""):
            pointer=0
            tags=list()
            for i in range(10):
                    tag=getfield("name",text,pointer)
                    size=getfield("count",text,pointer)
                    if(size!="" and tag!=""):
                            try:
                                    tags.append(tag[0])
                                   # print tag[0]

                            except ValueError,msg:
                                    derp=str(msg)[str(msg).find("ValueError"):]
                                    raise
                                    continue
                            pointer=size[1]
            genre_tag=makeid3(tags,1)
    if(genre_tag==""):
            pointer=0
            with open('failedgenres.txt','a') as f:
                    tags=list()
                    for i in range(10):
                            tag=getfield("name",text,pointer)
                            size=getfield("count",text,pointer)
                            if(size!="" and tag!=""):
                                    try:
                                            if("<" not in tag[0]):
                                                    f.write(tag[0]+"\n")
                                           # print tag[0]

                                    except ValueError,msg:
                                            derp=str(msg)[str(msg).find("ValueError"):]
                                            raise
                                            continue
                                    pointer=size[1]
            return ""
    else:
        return genre_tag
def parse_album(text):
    n_album_url=""
    pointer=text.find("<album")      
    if(pointer!=-1):
        album_tag=unicode(getfield("title",text,pointer)[0],'utf-8')
        if("utf-8" in album_tag):
            album_tag=""
        if("&amp" in album_tag):    
            album_tag[:album_tag.find("&")]+"&"+album_tag[album_tag.find("&")+5:]
    else:
        print "neither album nor pic available"
        return("no_album","no_picture")
    sizelist=['mega','extralarge','large']
    for item in sizelist:
        #print item
        album_url=getfield("image size=\""+item+"\"",text)
        if(album_url!="" and "noimage" not in album_url[0] and "utf-8" not in album_url[0]):
            n_album_url=album_url[0]
            break
    if n_album_url=="":
        picture="no_picture"
    else:
        #print n_album_url
        if ".jpg" in n_album_url or ".jpeg" in n_album_url:
            typ="jpeg"
        elif ".png" in n_album_url:
            typ="png"
        else:
            typ="jpeg"
        try:
            picture=urllib2.urlopen(n_album_url).read()
        except urllib2.HTTPError,e:
            print e.read()
            return("","no_picture")
        return (album_tag,picture,typ)
    return (album_tag,picture)

